package com.webserver.http;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HttpServletResponse {
    private Socket socket;
    private int statusCode = 200;
    private String statusReason = "OK";
    private File contentFile;
    private Map<String , String> headers = new HashMap<>();
    public HttpServletResponse(Socket socket){
        this.socket = socket;
    }


    public void response() throws IOException {
        sentStatusLine();
        sentHeaders();
        sentContent();
    }

    public void sentStatusLine() throws IOException {
        println("HTTP/1.1 "+statusCode+" "+statusReason);
    }

    public void sentHeaders() throws IOException {
        Set<Map.Entry<String , String>> entrySet = headers.entrySet();
        for (Map.Entry<String , String> entry : entrySet) {
            println(entry.getKey()+": "+entry.getValue());
        }
        println("");
    }

    public void sentContent() throws IOException {
        OutputStream out = socket.getOutputStream();
        FileInputStream fis = new FileInputStream(contentFile);
        int len;
        byte[] data = new byte[1024*10];
        while ((len = fis.read(data))!=-1){
            out.write(data,0,len);
        }
        System.out.println("相应发送完毕!!!");
    }

    private void println(String line) throws IOException {
        byte[] data = line.getBytes(StandardCharsets.ISO_8859_1);
        OutputStream out = socket.getOutputStream();
        out.write(data);
        out.write(13);
        out.write(10);
    }

    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public String getStatusReason() {
        return statusReason;
    }

    public void setStatusReason(String statusReason) {
        this.statusReason = statusReason;
    }

    public File getContentFile() {
        return contentFile;
    }

    public void setContentFile(File contentFile) {
        this.contentFile = contentFile;
        String contentType = null;
        try {
             contentType = Files.probeContentType(contentFile.toPath());

        } catch (IOException e) {
            e.printStackTrace();
        }
        if (contentType!=null){
            addHeader("Content-Type",contentType);
        }
        addHeader("Content-Length",contentFile.length()+"");
    }

    public void addHeader(String name , String value){
        headers.put(name,value);
    }
}
